package me.numark;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.model.News;
import me.numark.net.BaseResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.Constants;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

/**
 * Created by tian on 14/11/20:上午7:53.
 */
public class RecommendActivity extends BaseActivity implements View.OnClickListener {

    @InjectView(R.id.news_icon)
    ImageView newsIcon;

    @InjectView(R.id.news_title)
    TextView newsTitle;

    @InjectView(R.id.news_time)
    TextView newsTime;

    @InjectView(R.id.news_source)
    TextView newsSource;

    @InjectView(R.id.back)
    View back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_text)
    TextView rightButton;

    @InjectView(R.id.edit)
    EditText editText;

    @InjectView(R.id.news)
    View newsLayout;

    private News mNews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommend);
        ButterKnife.inject(this);
        try {
            mNews = new Gson()
                    .fromJson(getIntent().getStringExtra(Constants.NEWS_EXTRA), News.class);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            finish();
        }
        newsLayout.setBackgroundColor(
                getResources().getColor(R.color.recommend_news_item_color));
        back.setOnClickListener(this);
        rightButton.setOnClickListener(this);
        title.setText(R.string.recommend);
        rightButton.setText(R.string.publish);
        Picasso.with(this).load(mNews.face_img).into(newsIcon);
        Date today, yesterday, year;
        Date[] dates = Utils.getMarkDate();
        today = dates[0];
        yesterday = dates[1];
        year = dates[2];
        newsTime.setText(Utils.getTimeShowText(mNews.getDate(), yesterday, today, year));
        newsTitle.setText(mNews.title);
        newsSource.setText(mNews.from_str);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s != null && s.length() > 0) {
                    rightButton.setEnabled(true);
                } else {
                    rightButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                handleFinish();
                break;
            case R.id.right_text:
                submitNews();
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        handleFinish();
    }

    private void handleFinish() {
        if (TextUtils.isEmpty(editText.getText().toString())) {
            finish();
        } else {
            new AlertDialog.Builder(this).setTitle(R.string.confirm_discard)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    setResult(RESULT_CANCELED);
                                    finish();
                                }
                            }).setNegativeButton(android.R.string.cancel, null).show();
        }
    }

    private void submitNews() {
        String url = String.format(NetworkConstants.RECOMMEND_URL, Settings.getUid());
        Map<String, String> body = new HashMap<String, String>();
        body.put("nid", Integer.toString(mNews.id));
        body.put("description", editText.getText().toString());

        GsonRequest<BaseResponse> request = new GsonRequest<BaseResponse>(url, Request.Method.POST,
                BaseResponse.class, true, body, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                dismissProgress();
                if (response.ret) {
                    Toast.makeText(RecommendActivity.this, R.string.recommend_success,
                            Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();
                } else {
                    Toast.makeText(RecommendActivity.this, response.msg, Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissProgress();
                Toast.makeText(RecommendActivity.this, R.string.generic_network_error,
                        Toast.LENGTH_SHORT).show();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        showProgress(R.string.submitting);
    }
}
